package com.tiantianyuegou.adapter;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tiantianyuegou.activity.BaseActivity;
import com.tiantianyuegou.R;
import com.tiantianyuegou.activity.MyEvaluateActivity;
import com.tiantianyuegou.activity.PayActivity;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.MyGoodsModel;
import com.tiantianyuegou.model.ShopModel;
import com.tiantianyuegou.model.StoreModel;
import com.tiantianyuegou.util.AsyncImageLoader;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.SelfUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by huyang on 2016/1/19 0019.
 * 订单适配器
 */
public class OrderAdapter extends BaseAdapter implements View.OnClickListener {

//    private static final String sImageUrl = "http://fashion.qqread.com/ArtImage/20110225/0083_13.jpg";

    private static final int MSG_LOAD_SUCCESS = 0;
    private static final int MSG_LOAD_FAILURE = 1;

    private Button mLoadButton;
    private ProgressDialog mProgressBar;
    private ImageView mImageView;
    private ViewHolder viewHolder = new ViewHolder();

    private String OrderNo, GoodsName, GoodsPrice;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.i("UI thread", " >> handleMessage()");

            switch (msg.what) {
                case MSG_LOAD_SUCCESS:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    mImageView.setImageBitmap(bitmap);

                    mProgressBar.setProgress(100);
                    mProgressBar.setMessage("Image downloading success!");
                    mProgressBar.dismiss();
                    break;

                case MSG_LOAD_FAILURE:
                    mProgressBar.setMessage("Image downloading failure!");
                    mProgressBar.dismiss();
                    break;
            }
        }
    };

    private Context mContext;
    private List<StoreModel> mData;
    private List<JSONObject> shopList;
    private JSONArray goodList;
    private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();

    private String[] num = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
    private String[] strStatus = {"订单生成", "待发货", "已发货", "已收货", "已评价", "申请退款中", "已退款", "交易取消", "交易关闭"};
    private ShopModel shopModel;
    private MyGoodsModel myGoodsModel;
    private int fmPosition;
    private int item;

    private BaseActivity activity;
    private String TAG = "OrderAdapter";
    private LoadingDialog loadingDialog;
    private String Number;


    public int getPosition() {
        return item;
    }

    public interface OrderManage {
        void order();
    }

    public interface OrderDelete {
        void delete();
    }

    public interface OrderPay {
        void pay(int i, String OrderNo, String GoodsName, String GoodsPrice);
    }

    public interface OrderCancal {
        void cancal();
    }

    OrderManage orderManage;
    OrderDelete orderDelete;
    OrderPay orderPay;
    OrderCancal orderCancal;

    public void setOrderManage(OrderManage orderManage) {
        this.orderManage = orderManage;
    }

    public void setOrderDelete(OrderDelete orderDelete) {
        this.orderDelete = orderDelete;
    }

    public void setOrderPay(OrderPay orderPay) {
        this.orderPay = orderPay;
    }

    public void setOrderCancal(OrderCancal orderCancal) {
        this.orderCancal = orderCancal;
    }

    public OrderAdapter(Context mContext) {
        this.mContext = mContext;
        shopList = new ArrayList<>();
        shopModel = new ShopModel();
    }

    public OrderAdapter(Context context, List<JSONObject> shopList) {
        this.mContext = context;
        this.shopList = shopList;
    }

    public void setData(List<JSONObject> shopList, int position) {
        this.shopList.clear();
        this.shopList.addAll(shopList);
        fmPosition = position;
        Log.e("adapter", "getCount" + shopList.size());
    }

//    public void setI(int item){
//        this.item=item;
//    }

    @Override
    public int getCount() {

        return shopList.size();
    }

    @Override
    public Object getItem(int position) {
        return shopList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public View getView(int position, View converView, ViewGroup parent) {
        ViewHolder holder = null;
        String picUrl = "";
        shopModel = new ShopModel();
        myGoodsModel = new MyGoodsModel();
        if (converView == null) {
            converView = LayoutInflater.from(mContext).inflate(R.layout.item_order_status, null);
            holder = new ViewHolder();
            holder.storeName = (TextView) converView.findViewById(R.id.item_order_store_name);
            holder.sotreImg= (ImageView) converView.findViewById(R.id.item_order_store_img);
            holder.googsNum = (TextView) converView.findViewById(R.id.goods_num);
            holder.orderStatus = (TextView) converView.findViewById(R.id.order_status);
            holder.orderPaid = (TextView) converView.findViewById(R.id.order_paid);
            holder.linear = (LinearLayout) converView.findViewById(R.id.item_order_linear);
            holder.cancel = (Button) converView.findViewById(R.id.btn_cancel);
            holder.pay = (Button) converView.findViewById(R.id.btn_pay);
            holder.btn_shouhuo = (Button) converView.findViewById(R.id.btn_shouhuo);
            holder.btn_delete = (Button) converView.findViewById(R.id.btn_delete);
            holder.btn_evaluate = (Button) converView.findViewById(R.id.btn_evaluate);
            holder.btn_delete2 = (Button) converView.findViewById(R.id.btn_delete2);
            holder.btn_fahuo = (Button) converView.findViewById(R.id.btn_fahuo);
            converView.setTag(holder);
        } else {
            holder = (ViewHolder) converView.getTag();

        }

        holder.cancel.setTag(position);
        holder.pay.setTag(position);
        holder.btn_shouhuo.setTag(position);
        holder.btn_delete.setTag(position);
        holder.btn_evaluate.setTag(position);
        holder.btn_delete2.setTag(position);
        holder.btn_fahuo.setTag(position);

        String status = "";
        Log.e("adapter", "getView");

        try {
            status = shopList.get(position).getString("toStatus");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if("member".equals(SPHelper.getTYPE())){
            holder.sotreImg.setImageResource(R.mipmap.store);
          //  holder.storeName.setText();
        }else if("seller".equals(SPHelper.getTYPE())){
            holder.sotreImg.setImageResource(R.mipmap.d_6);
           // holder.storeName.setText("");
        }

        if ("member".equals(SPHelper.getTYPE())) {
            holder.btn_fahuo.setVisibility(View.GONE);
            if ("1".equals(status)) {
                holder.cancel.setVisibility(View.VISIBLE);
                holder.pay.setVisibility(View.VISIBLE);
                holder.btn_shouhuo.setVisibility(View.GONE);
                holder.btn_delete.setVisibility(View.GONE);
                holder.btn_evaluate.setVisibility(View.GONE);
                holder.btn_delete2.setVisibility(View.GONE);
            } else if ("2".equals(status) || "6".equals(status)) {
                holder.cancel.setVisibility(View.GONE);
                holder.pay.setVisibility(View.GONE);
                holder.btn_shouhuo.setVisibility(View.GONE);
                holder.btn_delete.setVisibility(View.GONE);
                holder.btn_evaluate.setVisibility(View.GONE);
                holder.btn_delete2.setVisibility(View.GONE);
            } else if ("3".equals(status)) {
                holder.cancel.setVisibility(View.GONE);
                holder.pay.setVisibility(View.GONE);
                holder.btn_shouhuo.setVisibility(View.VISIBLE);
                holder.btn_delete.setVisibility(View.GONE);
                holder.btn_evaluate.setVisibility(View.GONE);
                holder.btn_delete2.setVisibility(View.GONE);
            } else if ("4".equals(status)) {
                holder.cancel.setVisibility(View.GONE);
                holder.pay.setVisibility(View.GONE);
                holder.btn_delete.setVisibility(View.VISIBLE);
                holder.btn_evaluate.setVisibility(View.VISIBLE);
                holder.btn_delete2.setVisibility(View.GONE);
            } else if ("7".equals(status) || "8".equals(status) || "9".equals(status)||"5".equals(status)) {
                holder.cancel.setVisibility(View.GONE);
                holder.pay.setVisibility(View.GONE);
                holder.btn_delete2.setVisibility(View.VISIBLE);
                holder.btn_shouhuo.setVisibility(View.GONE);
                holder.btn_delete.setVisibility(View.GONE);
                holder.btn_evaluate.setVisibility(View.GONE);
            }
        } else if ("seller".equals(SPHelper.getTYPE())) {
            holder.cancel.setVisibility(View.GONE);
            holder.pay.setVisibility(View.GONE);
            holder.btn_shouhuo.setVisibility(View.GONE);
            holder.btn_delete.setVisibility(View.GONE);
            holder.btn_evaluate.setVisibility(View.GONE);
            if ("2".equals(status)) {
                holder.btn_fahuo.setVisibility(View.VISIBLE);
                holder.btn_delete2.setVisibility(View.GONE);
            } else if ("8".equals(status) || "9".equals(status)) {
                holder.btn_fahuo.setVisibility(View.GONE);
                holder.btn_delete2.setVisibility(View.VISIBLE);
            } else {
                holder.btn_fahuo.setVisibility(View.GONE);
                holder.btn_delete2.setVisibility(View.GONE);
            }
        }

        converView = jsonShop(holder, converView, position);


        item = position - 1;

        holder.cancel.setOnClickListener(this);
        holder.pay.setOnClickListener(this);

        holder.btn_shouhuo.setOnClickListener(this);
        holder.btn_delete.setOnClickListener(this);
        holder.btn_evaluate.setOnClickListener(this);
        holder.btn_delete2.setOnClickListener(this);
        holder.btn_fahuo.setOnClickListener(this);

        return converView;
    }

    private View jsonShop(ViewHolder viewHolder, View view, int position) {
        ViewHolder holder = viewHolder;
        try {


            String status = shopList.get(position).getString("toStatus");


            if("member".equals(SPHelper.getTYPE())){
                holder.storeName.setText(shopList.get(position).getString("tsName"));
            }else if("seller".equals(SPHelper.getTYPE())){
                 holder.storeName.setText(shopList.get(position).getString("tmName"));
            }

            holder.googsNum.setText("共 " + shopList.get(position).getString("toTotalCount") + " 件");

            holder.orderPaid.setText("实付款：￥" +new DecimalFormat("0.00").format (Double.valueOf(shopList.get(position).getString("toPayPrice"))));


            for (int i = 0; i < num.length; i++) {
                if (status.equals(num[i])) {
                    holder.orderStatus.setText(strStatus[i]);
                }
            }

            goodList = shopList.get(position).getJSONArray("products");


        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("adapter", "      try catch");
            goodList = new JSONArray();
        }


        holder.linear.removeAllViews();
        for (int goods = 0; goods < goodList.length(); goods++) {
            try {
                JSONObject jsonGoods = goodList.getJSONObject(goods);
                View view2 = LayoutInflater.from(mContext).inflate(R.layout.item_order, null);

                String pic = jsonGoods.get("tpPic").toString();
                if (pic.contains(",")) {
                    pic = pic.substring(0, pic.indexOf(","));
                }
                ImageLoader.getInstance().displayImage(pic, (ImageView) view2.findViewById(R.id.item_order_img));

                ((TextView) view2.findViewById(R.id.item_order_name)).setText(jsonGoods.getString("tpName"));
                Double price= Double.valueOf(jsonGoods.getString("todPrice"));
                ((TextView) view2.findViewById(R.id.item_order_price)).setText("￥" +new DecimalFormat("0.00").format(price));
                ((TextView) view2.findViewById(R.id.item_order_num)).setText("x" + jsonGoods.getString("todCount"));


                String spec = jsonGoods.getString("todSpecJson");
                if (spec.contains("[")) {
                    String strInfo = new String();


                    try {
                        JSONArray goodsInfo = new JSONArray(jsonGoods.getString("todSpecJson"));


                        //Log.e("adapter", goodsInfo.toString());
                        for (int info = 0; info < goodsInfo.length(); info++) {
                            JSONObject objectInfo = goodsInfo.getJSONObject(info);
                            strInfo += (objectInfo.getString("tsName") + ":");
                            strInfo += (objectInfo.getString("value"));
                            strInfo += ("\t\t");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //Log.e("adapter", "strInfo    " + strInfo);
                    ((TextView) view2.findViewById(R.id.text_order_color)).setText(strInfo);

                } else {
                    ((TextView) view2.findViewById(R.id.text_order_color)).setText("");

                }
                holder.linear.addView(view2);
            } catch (Exception e) {
                e.printStackTrace();
                //Log.e("adapter", "      try catch2");
            }
        }
        return view;
    }

    @Override
    public boolean areAllItemsEnabled() {
        // all items are separator
        return true;
    }

    @Override
    public boolean isEnabled(int position) {
        // all items are separator
        return true;
    }

    @Override
    public void onClick(View view) {
        int index = (Integer) view.getTag();
        item = index;
        try {
            Number = shopList.get(item).getString("toNumber");
            OrderNo = shopList.get(item).getString("toNumber");
            GoodsName = shopList.get(item).getString("tsName");
            GoodsPrice = shopList.get(item).getString("toPayPrice");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            SPHelper.setToId(shopList.get(index).getString("toId"));
            SPHelper.setTSId(shopList.get(index).getString("tsId"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        switch (view.getId()) {
            case R.id.btn_cancel:
                orderCancal.cancal();
                break;

            case R.id.btn_pay:
                Intent pay = new Intent(mContext, PayActivity.class);
                pay.putExtra("orderNo", Number);
                pay.putExtra("orderId", SPHelper.getToId());
                mContext.startActivity(pay);
                break;
            case R.id.btn_shouhuo:
                orderPay.pay(2,OrderNo,GoodsName,GoodsPrice);
                break;
            case R.id.btn_delete:
                orderDelete.delete();
                break;
            case R.id.btn_evaluate:
                Intent intent = new Intent(mContext, MyEvaluateActivity.class);
                intent.putExtra("products", shopList.get(index).toString());
                mContext.startActivity(intent);
                break;
            case R.id.btn_delete2:
                orderDelete.delete();
                break;

            case R.id.btn_fahuo:
                orderManage.order();
                break;

            default:
                break;
        }
    }

    private void loadDelete() {
        loadingDialog = new LoadingDialog(mContext);
        loadingDialog.setMsg("请稍等");
        loadingDialog.showDialog();
        RequestParams params = new RequestParams();

        params.addBodyParameter("toId", SPHelper.getToId());
        Log.e("toid", ",toId     " + SPHelper.getToId());

        activity = (BaseActivity) mContext;
        if ("member".equals(SPHelper.getTYPE())) {
            params.addBodyParameter("tmId", SPHelper.getTmId());
            activity.loadData(HttpRequest.HttpMethod.POST, ApiDefine.ORDER_DELTE, params, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    String response = responseInfo.result;
                    Log.e(TAG, TAG + "     " + response);
                    Log.e(TAG, TAG + "toId     " + SPHelper.getToId());
                    try {
                        JSONObject object = new JSONObject(response);
                        activity.showMsg(object.getString("message"));
                        if ("100".equals(object.getString("code"))) {
                            orderDelete.delete();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    loadingDialog.dismiss();
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    loadingDialog.dismiss();
                }
            });
        } else if ("seller".equals(SPHelper.getTYPE())) {
            params.addBodyParameter("tmId", SPHelper.getTSId());
            params.addBodyParameter("password", new SelfUtils().getMD5(SPHelper.getPassword()));
            activity.loadData(HttpRequest.HttpMethod.POST, ApiDefine.STORE_ORDER_DELET, params, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    String response = responseInfo.result;
                    Log.e(TAG, TAG + "   " + response);
                    try {
                        JSONObject object = new JSONObject(response);
                        activity.showMsg(object.getString("message"));
                        if ("100".equals(object.getString("code"))) {
                            orderDelete.delete();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    loadingDialog.dismiss();
                }

                @Override
                public void onFailure(HttpException e, String s) {

                    loadingDialog.dismiss();
                }
            });
        }
    }

    private void loadCancal() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", SPHelper.getTmId());
        params.addBodyParameter("toId", SPHelper.getToId());

        activity = (BaseActivity) mContext;
        activity.loadData(HttpRequest.HttpMethod.POST, ApiDefine.ORDER_CANCEL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response = responseInfo.result;

                Log.e(TAG, TAG + "   " + response);
                try {
                    JSONObject object = new JSONObject(response);
                    activity.showMsg(object.getString("message"));
                    if ("100".equals(object.getString("code"))) {
                        orderCancal.cancal();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    private void loadPay() {

      //  orderPay.pay(1);

    }

    class ViewHolder {
        ImageView sotreImg;
        TextView storeName;
        TextView orderStatus;
        TextView googsNum;
        TextView orderPaid;
        LinearLayout linear;
        Button cancel;
        Button pay;
        Button btn_shouhuo;
        Button btn_delete;
        Button btn_evaluate;
        Button btn_delete2;
        Button btn_fahuo;

    }
}